package com.zhouxiao.multithreading.kfc;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 周明阳
 * mail:gqzmy@outlook.com
 * 时间:2018-03-13 16:47
 */

public class Kfc {

    private String[] name = {"薯条", "可乐", "鸡翅", "汉堡"};

    private static final int Max = 20;

    private List<Food> foods = new ArrayList<>();

    /*生产食物*/
    public void prod(int index) {
        synchronized (this) {
            while (foods.size() > Max) {
                System.out.println("食材够了");
                this.notifyAll();
                try {
                    String name = Thread.currentThread().getName();
                    this.wait();
                    System.out.println("生产者： " + name);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(" 生产食物");
            for (int i = 0; i < index; i++) {
                Food food = new Food(name[(int) (Math.random() * 4)]);
                foods.add(food);
                System.out.println("生产了" + food.getName() + foods.size());
            }
        }
    }

    /*消费食物*/
    public void consu(int index) {
        synchronized (this) {
            while (foods.size() < index) {
                System.out.println("食材不够了");
                this.notifyAll();
                try {
                    String name = Thread.currentThread().getName();
                    this.wait();
                    System.out.println("消费者：" + name);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            System.out.println("开始消费");
            for (int i = 0; i < index; i++) {
                Food food = foods.remove(foods.size() - 1);
                System.out.println("消费了一个" + food.getName() + foods.size());
            }
        }
    }
}
